package com.gxnu.edu.cn.client.controller;

import com.gxnu.edu.cn.ttxxt.entity.Notifications;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class NotificationClient {
    @Autowired
    private RestTemplate restTemplate;

    private String baseUrl = "http://localhost:8080";

    public CompletableFuture<List<Notifications>> getNotificationsFrendApple(Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 创建请求头，明确指定字符编码
                HttpHeaders headers = new HttpHeaders();
                headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
                headers.setContentType(MediaType.APPLICATION_JSON);

                // 创建 HttpEntity 对象，包含请求头
                HttpEntity<?> entity = new HttpEntity<>(headers);

                // 使用 exchange 方法代替 getForEntity，以便可以设置请求头和处理泛型响应类型
                ResponseEntity<List<Notifications>> response = restTemplate.exchange(
                        baseUrl + "/api/notifications/user/friend/" + userId,
                        HttpMethod.GET,
                        entity,
                        new ParameterizedTypeReference<List<Notifications>>() {}
                );

                return response.getBody();
            } catch (HttpStatusCodeException e) {
                // 处理 HTTP 状态码异常，获取响应内容
                String responseBody = e.getResponseBodyAsString();
                throw new RuntimeException("获取好友申请通知失败，HTTP状态码: " + e.getStatusCode() +
                        ", 响应内容: " + responseBody, e);
            } catch (Exception e) {
                throw new RuntimeException("获取好友申请通知失败: " + e.getMessage(), e);
            }
        });
    }


    public CompletableFuture<List<Notifications>> getNotifications(Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 创建请求头，明确指定字符编码
                HttpHeaders headers = new HttpHeaders();
                headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
                headers.setContentType(MediaType.APPLICATION_JSON);

                // 创建 HttpEntity 对象，包含请求头
                HttpEntity<?> entity = new HttpEntity<>(headers);

                // 使用 exchange 方法代替 getForEntity，以便可以设置请求头和处理泛型响应类型
                ResponseEntity<List<Notifications>> response = restTemplate.exchange(
                        baseUrl + "/api/notifications/user/" + userId,
                        HttpMethod.GET,
                        entity,
                        new ParameterizedTypeReference<List<Notifications>>() {}
                );

                return response.getBody();
            } catch (HttpStatusCodeException e) {
                // 处理 HTTP 状态码异常，获取响应内容
                String responseBody = e.getResponseBodyAsString();
                throw new RuntimeException("获取通知失败，HTTP状态码: " + e.getStatusCode() +
                        ", 响应内容: " + responseBody, e);
            } catch (Exception e) {
                throw new RuntimeException("获取通知失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<List<Notifications>> getUnreadNotifications(Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<List> response = restTemplate.getForEntity(
                        baseUrl + "/api/notifications/user/" + userId + "/unread",
                        List.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("获取未读通知失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> markNotificationAsRead(Long notificationId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<Map> response = restTemplate.exchange(
                        baseUrl + "/api/notifications/" + notificationId + "/read",
                        HttpMethod.POST,
                        null,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("标记通知为已读失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> markAllNotificationsAsRead(Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/notifications/user/" + userId + "/read-all",
                        null,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("标记所有通知为已读失败: " + e.getMessage(), e);
            }
        });
    }

    // 获取当前用户发出的通知（申请）
    public CompletableFuture<List<Notifications>> getMySentNotifications(Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<List> response = restTemplate.getForEntity(
                        baseUrl + "/api/notifications/sent/" + userId,
                        List.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("获取发出的通知失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> acceptFriendRequest(Long notificationId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Map<String, Object> request = Map.of(
                        "status", 2
                );
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/notifications/" + notificationId + "/process",
                        entity,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("接受好友申请失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> rejectFriendRequest(Long notificationId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Map<String, Object> request = Map.of("status", 3);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/notifications/" + notificationId + "/reject",
                        entity,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("拒绝好友申请失败: " + e.getMessage(), e);
            }
        });
    }

    // 处理群组申请（接受）
    public CompletableFuture<Map<String, Object>> acceptGroupRequest(Long notificationId, Long groupId, Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Map<String, Object> request = Map.of(
                        "status", 2, // 2表示已接受
                        "groupId", groupId,
                        "userId", userId
                );
                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/groups/requests/" + notificationId + "/process",
                        request,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("接受群组申请失败: " + e.getMessage(), e);
            }
        });
    }

    // 处理群组申请（拒绝）
    public CompletableFuture<Map<String, Object>> rejectGroupRequest(Long notificationId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Map<String, Object> request = Map.of("status", 3); // 3表示已拒绝
                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/groups/requests/" + notificationId + "/process",
                        request,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("拒绝群组申请失败: " + e.getMessage(), e);
            }
        });
    }
    public CompletableFuture<Map<String, Object>> processNotification(Long notificationId, Integer status) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Map<String, Integer> request = Map.of("status", status);
                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/notifications/" + notificationId + "/process",
                        request,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("处理通知失败: " + e.getMessage(), e);
            }
        });
    }
}